<script setup>
import { ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { addDepartmentApi } from '@/service/user.js'; // 假设你有一个添加部门的 API
const emit = defineEmits(['reload']);
const reloadDptTree = () => {
  emit('reload');
}

const dialogVisible = ref(false);
const parentTitle = ref('');

const form = ref({
  id: '',
  parent_id: '',
  title: ''
});

// 设置form的验证规则
const rules = ref({
  title: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ]
});

// 初始化form
const initForm = () => {
  form.value = {
    id: '',
    parent_id: '',
    title: ''
  };
};

const openDialog = (department) => {
  parentTitle.value = department.label;
  form.value = {
    id: '',
    parent_id: department.id,
    title: ''
  };
  dialogVisible.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
  initForm();
};

const formRef = ref(null);
const handleSave = () => {
  // 表单验证后提交
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await addDepartmentApi(form.value);
        if (response.code === 200) {
          ElMessage.success(response.message);
          closeDialog();
          reloadDptTree();
        } else {
          ElMessage.error(response.message);
        }
      } catch (error) {
        ElMessage.error('添加部门失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 暴漏给父组件的方法
defineExpose({
  openDialog
});
</script>

<template>
  <el-dialog v-model="dialogVisible" title="添加部门" width="300">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-form-item label="父级部门">
        <el-input :value="parentTitle"></el-input>
      </el-form-item>
      <el-form-item label="部门名称">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 添加一些样式以适应你的需求 */
</style>
